package com.qinggeng.project.system.service.impl;

import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.redenvelop.BigDecimalUtil;
import com.qinggeng.project.api.dto.OrdersUserDto;
import com.qinggeng.project.system.domain.GoodsPercent;
import com.qinggeng.project.system.domain.Orders;
import com.qinggeng.project.system.domain.OrdersGoods;
import com.qinggeng.project.system.domain.vo.CourierRefundOrdersVO;
import com.qinggeng.project.system.mapper.OrdersGoodsMapper;
import com.qinggeng.project.system.mapper.OrdersMapper;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单商品Service业务层处理
 *
 * @author qinggeng
 * @date 2020-06-17
 */
@Service
@Slf4j
public class OrdersGoodsServiceImpl implements IOrdersGoodsService
{


    public   static  final  Integer CANCEL =0;

    public   static  final  Integer REFUND =1;

    public   static  final  Integer AGREE =2;

    public   static  final  Integer REFUSE =3;

    public   static  final String  STATUS="30";
    public   static  final String  PAY_STATUS="20";
    public   static  final String  DIST_SHOP_STATUS="20";
    public   static  final String  EVAL_STATUS= "10";

    private static final BigDecimal ZERO=new BigDecimal(0);

    private static  final BigDecimal ONE=new BigDecimal(1);

    public static final String PERCENTAGE_KEY="sys.orders.percentage";


    @Resource
    private OrdersGoodsMapper ordersGoodsMapper;
    @Autowired
    private IOrdersEvaluateService ordersEvaluateService;

    @Resource
    private OrdersMapper ordersMapper;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsPercentService goodsPercentService;

    /**
     * 查询订单商品
     *
     * @param ordersGoodsId 订单商品ID
     * @return 订单商品
     */
    @Override
    public OrdersGoods selectOrdersGoodsById(Long ordersGoodsId)
    {
        return ordersGoodsMapper.selectOrdersGoodsById(ordersGoodsId);
    }

    /**
     * 查询订单商品列表
     *
     * @param ordersGoods 订单商品
     * @return 订单商品
     */
    @Override
    public List<OrdersGoods> selectOrdersGoodsList(OrdersGoods ordersGoods)
    {
        return ordersGoodsMapper.selectOrdersGoodsList(ordersGoods);
    }

    /**
     * 新增订单商品
     *
     * @param ordersGoods 订单商品
     * @return 结果
     */
    @Override
    public int insertOrdersGoods(OrdersGoods ordersGoods)
    {
        return ordersGoodsMapper.insertOrdersGoods(ordersGoods);
    }

    /**
     * 修改订单商品
     *
     * @param ordersGoods 订单商品
     * @return 结果
     */
    @Override
    public int updateOrdersGoods(OrdersGoods ordersGoods)
    {
        return ordersGoodsMapper.updateOrdersGoods(ordersGoods);
    }

    /**
     * 批量删除订单商品
     *
     * @param ordersGoodsIds 需要删除的订单商品ID
     * @return 结果
     */
    @Override
    public int deleteOrdersGoodsByIds(Long[] ordersGoodsIds)
    {
        return ordersGoodsMapper.deleteOrdersGoodsByIds(ordersGoodsIds);
    }

    /**
     * 删除订单商品信息
     *
     * @param ordersGoodsId 订单商品ID
     * @return 结果
     */
    @Override
    public int deleteOrdersGoodsById(Long ordersGoodsId)
    {
        return ordersGoodsMapper.deleteOrdersGoodsById(ordersGoodsId);
    }

    @Override
    public List<OrdersGoods> selectOrderGoodListByOrdersId(Long orderId) {
        return ordersGoodsMapper.selectOrderGoodListByOrdersId(orderId);
    }

    /**
     * 根据订单id集合查询所有相关的订单商品信息
     * @param orderIdList
     */
    @Override
    public List<OrdersGoods> selectOrderGoodListByOrdersIds(List<Long> orderIdList) {
        List<OrdersGoods>  list=ordersGoodsMapper.selectOrderGoodListByOrdersIds(orderIdList);
        return list;
    }

    @Override
    public BigDecimal getOrdersPercentageByOrdersId(Long ordersId) {
        BigDecimal percentage=ordersGoodsMapper.getOrdersPercentageByOrdersId(ordersId);
        return percentage!=null?percentage:new BigDecimal(0);
    }




    @Override
    public BigDecimal getOrdersAverageProfitRateByOrdersId(Long ordersId) {
        return ordersGoodsMapper.getOrdersAverageProfitRateByOrdersId(ordersId);
    }

    @Override
    public Long getBuyUserNumByMainCategory(Long mainCategory){
        return ordersGoodsMapper.getBuyUserNumByMainCategory(mainCategory);
    }

    @Override
    public Long getOrdersGoodsNumByMainCategory(Long mainCategory) {
        return ordersGoodsMapper.getOrdersGoodsNumByMainCategory(mainCategory);
    }

    @Override
    public List<OrdersUserDto> listOrdersUserDto(Long mainCategory) {
        return ordersGoodsMapper.listOrdersUserDto(mainCategory);
    }

    @Override
    public BigDecimal calculation(Long ordersGoodsId, Long userId) {
        OrdersGoods ordersGoods= selectOrdersGoodsById(ordersGoodsId);
        if (null == ordersGoods){
            throw  new CustomException("商品不存在");
        }
        Long orderId=ordersGoods.getOrdersId();
        Orders orders=ordersMapper.selectOrdersById(orderId);
        if (null == orders){
            throw  new CustomException("订单不存在");
        }
         Long orderUserId= orders.getUserId();
         if (!userId.equals(orderUserId)){
             throw  new CustomException("用户与该订单不匹配");
         }
        BigDecimal price=ordersGoods.getGoodsPrice();
        Integer num=ordersGoods.getGoodsNum();
        BigDecimal sumPrice=BigDecimalUtil.multiply(price,new BigDecimal(num)).setScale(2,BigDecimal.ROUND_UP);
        return sumPrice;
    }

    @Override
    public boolean sigleItemRefund(Long ordersGoodsId) {
        OrdersGoods ordersGoods= selectOrdersGoodsById(ordersGoodsId);
        if (null == ordersGoods){
            throw  new CustomException("商品不存在");
        }
        Long orderId=ordersGoods.getOrdersId();
        Orders orders=ordersMapper.selectOrdersById(orderId);
        if (null == orders){
            throw  new CustomException("订单不存在");
        }
        if (orders.getStatus().equals(STATUS)==false){
            throw  new CustomException("不是完成状态无法退款");
        }

        if (orders.getPayStatus().equals(PAY_STATUS)==false){
            throw  new CustomException("该订单没有支付无法退款");
        }
        int size=ordersGoodsMapper.updateSingleItemRefund(ordersGoodsId,REFUND);
        return size>=1;
    }


    @Override
    public boolean sigleItemRefundAgree(Long ordersGoodsId) {

        return ordersGoodsMapper.updateSingleItemRefund(ordersGoodsId,AGREE)>=1;
    }

    @Override
    public boolean sigleItemRefundRefuse(Long ordersGoodsId) {

        return ordersGoodsMapper.updateSingleItemRefund(ordersGoodsId,REFUSE)>=1;
    }

    /**
     * 退款商品
     * @param orderIdList
     * @return
     */
    @Override
    public List<OrdersGoods> selectReturnOrderGoodListByOrdersIds(List<Long> orderIdList) {
        return ordersGoodsMapper.selectReturnOrderGoodListByOrdersIds(orderIdList);
    }

    @Override
    public boolean updateOrdersGoodsByOrdersId(Long ordersId) {
        return ordersGoodsMapper.updateOrdersGoodsByOrdersId(ordersId);
    }

    @Override
    public boolean updateOrdersGoodsCancel(Long ordersGoodsId) {
        return ordersGoodsMapper.updateSingleItemRefund(ordersGoodsId,CANCEL)>=1;
    }

    public boolean checkOrdersGoodsIsAllEnd(Long ordersId){

        //查询该订单下的所有商品
        List<OrdersGoods> ordersGoodsList=ordersGoodsMapper.selectOrderGoodListByOrdersId(ordersId);
        if(CollectionUtils.isEmpty(ordersGoodsList)){
            throw new CustomException("订单商品为空");
        }
        int endCount=0;
        for (OrdersGoods ordersGoods :ordersGoodsList) {
            if(ordersGoods.getSingleItemRefund()==1){
                continue;
            }
            if(ordersGoods.getSingleItemRefund()==0
                &&!ordersGoods.getEvalStatus().equals(CommonEnum.STATUS_20.getValue())){
                continue;
            }
            endCount++;
        }
       return ordersGoodsList.size()==endCount;
    }

    @Override
    public OrdersGoods setProfitAndPercentage(BigDecimal buyPrice,OrdersGoods ordersGoods){
        if(null==ordersGoods){
            throw new CustomException("ordersGoods is null");
        }
        //单商品利润
        BigDecimal profit=null;
        if(buyPrice!=null){
            profit=goodsService.getProfitByBuyPrice(buyPrice,ordersGoods.getGoodsPrice());
        }
        //商品提成比
        BigDecimal percent=ordersGoods.getPercent();

        if(profit!=null&&percent!=null){
            ordersGoods.setProfit(this.getOrdersGoodsProfit(profit,ordersGoods.getGoodsNum(),ordersGoods.getDiscountPrice()));
            ordersGoods.setPercentage(this.getOrdersGoodsPercentage(ordersGoods.getProfit(),percent));
            return ordersGoods;
        }

        GoodsPercent goodsPercent=goodsPercentService.selectGoodsPercentByGoodsId(ordersGoods.getGoodsId());
        if(null==profit){
            BigDecimal profitRate=goodsPercent!=null?goodsPercent.getProfitRate():ZERO;
            profit=goodsService.getProfitByProfitRate(ordersGoods.getGoodsPrice(),profitRate);
        }
        if(null==percent){
            percent=goodsPercent!=null?goodsPercent.getPercent():ZERO;
        }
        ordersGoods.setProfit(this.getOrdersGoodsProfit(profit,ordersGoods.getGoodsNum(),ordersGoods.getDiscountPrice()));
        ordersGoods.setPercentage(this.getOrdersGoodsPercentage(ordersGoods.getProfit(),percent));
        return ordersGoods;
    }

    /**
     * 计算订单商品的利润
     * @param profit
     * @param goodsNum
     * @param reducePrice
     * @return
     */
    private BigDecimal getOrdersGoodsProfit(BigDecimal profit,Integer goodsNum,BigDecimal reducePrice){
        //单商品利润
        if(null==profit){
            throw new CustomException("profit is null");
        }
        if(profit.compareTo(ZERO)==0){
            return ZERO;
        }
        if(null==goodsNum||goodsNum<=1){
            return profit;
        }
        //总利润=单个利润*数量
        BigDecimal totalProfit=profit.multiply(new BigDecimal(goodsNum));
        //优惠价格
        if(null==reducePrice||reducePrice.compareTo(ZERO)<=0){
            return totalProfit;
        }
        if(reducePrice.compareTo(totalProfit)>=0){
            return ZERO;
        }
        //总利润=利润-优惠价格
        return totalProfit.subtract(reducePrice);

    }

    /**
     * 计算订单商品的团长提成
     * @param totalProfit
     * @param percent
     * @return
     */
    private BigDecimal getOrdersGoodsPercentage(BigDecimal totalProfit,BigDecimal percent){

        if(null==totalProfit){
            throw new CustomException("totalProfit is null");
        }
        if(totalProfit.compareTo(ZERO)<=0){
            return ZERO;
        }
        if(null==percent){
            throw new CustomException("percent is null");
        }
        if(percent.compareTo(ZERO)<=0){
            return ZERO;
        }
        return totalProfit.multiply(percent);

    }

    @Override
    public List<CourierRefundOrdersVO> selectCourierRefundOrdersVOListByCourierId(Long courierId,String refundAplStatus) {
        return ordersGoodsMapper.selectCourierRefundOrdersVOListByCourierId(courierId,refundAplStatus);
    }

    @Override
    public boolean updateRefundAplStatusByordersId(Long ordersGoodsId, String refundAplStatus) {
        int i = ordersGoodsMapper.updateRefundAplStatusByordersId(ordersGoodsId, refundAplStatus);
        if (i<1){
            return false;
        }
        return true;
    }

    @Override
    public boolean updateByRefundAplDelByordersGoodsId(Long ordersGoodsId, String refundAplDel) {
        int i = ordersGoodsMapper.updateByRefundAplDelByordersGoodsId(ordersGoodsId, refundAplDel);
        if (i<1){
            return false;
        }
        return true;
    }
}
